home *** CD-ROM | disk | FTP | other *** search
- Path: hubcap.clemson.edu!hubcap!mjs
- From: mjs@hubcap.clemson.edu (M. J. Saltzman)
- Newsgroups: comp.lang.c
- Subject: Re: Array indexing with malloc
- Date: 19 Apr 96 15:24:33 GMT
- Organization: Clemson University
- Message-ID: <mjs.829927473@hubcap>
- References: <96110.093936F0O@psuvm.psu.edu>
- NNTP-Posting-Host: hubcap.clemson.edu
- X-Newsreader: NN version 6.5.0 #1
-
- Tim Benner <F0O@psuvm.psu.edu> writes:
-
- >Hi netters!
-
- > I write c programs to collect online data, and I always malloc a block
- >of memory to hold the data. I set the memory block up such that each
- >row is a different time point, and each column is a different channel.
- > The formula I use to do this is:
- > RawData[CurrentPoint*NumChannels+Channel]
- > This works fine, except I don't like having to do the multiplication
- >every time I want to access a point in the memory block. I tried setting
-
- If the number of channels is known at compile time, you could do this:
-
- data_t (*RawData)[NUM_CHANNELS];
-
- RawData = malloc(NUM_POINTS * NUM_CHANNELS * sizeof(data_t));
-
- RawData[CurrentPoint][Channel] ...
-
- Otherwise, you could use a dynamic multidimensional array (as described
- in the FAQ), and access it the same way.
-
- >up the memory block by mallocing a structure. This also works, and I
- >believe is neater in implementation, but seems to have a limit of about
- >64k. I allocate arrays of around 100k or more.
- > My burning question is, can I use a structure rather then the above
- >method for accessing large arrays? I'm using Turbo C++ version 3.0, and
-
- Do you mean soemthing like
-
- struct point_t {
- data_t channel1, channel2, ..., channeln;
- } *RawData;
-
- RawData = malloc(NUM_POINTS * sizeof(struct point_t));
-
- RawData[i].channel1 ...
- etc.
-
- You could do this, but you lose the ability to loop over channels.
- If that's not what you had in mind, post some code.
-
- Note that all the address calculations involve that multiplication (or
- something similar), at least behind the scenes.
- --
- Matthew Saltzman
- Clemson University Math Sciences
- mjs@clemson.edu
-